const { logger } = require("../config/logConfig")

const Issue = require("../models/Issue")
const utils = require('../config/utils')
const Tags = require("../models/Tags")

// 列表
async function issueList (req, res) {
  let condition = utils.listSelect(req.body)
  let pageObj = utils.pageSelect(req.body)
  try {
    const issue = await Issue.findAndCountAll({
      offset: pageObj.skip,
      limit: pageObj.limit,
      where: condition,
      order: [['createdAt', 'DESC']],
      distinct: true,
      attributes: {
        exclude: ["createdAt", "updatedAt"],
      },
      include: [
        {
          model: Tags,
          as: 'tags'
        }
      ]
    })
    if (!issue) {
      utils.responseContent(res, 'OK', 200, data = { list: [], total: 0, pageSize: 10, pageNum: 1 })
    }
    let list = issue.rows.map((item, index) => ({
      id: item.id,
      question_name: item.question_name,
      question_from: item.question_from,
      question_cid: item.question_cid,
      question_address: item.question_address,
      tags: issue.rows[index]['tags.name'],
      author: item.author,
      answer: item.answer,
      rmk: item.rmk,
      stats: item.stats,
      ctime: item.ctime,
      del: item.del,
    }))
    utils.responseContent(res, 'OK', 200, data = {
      list,
      pageNum: (pageObj.skip / pageObj.limit) + 1,
      pageSize: pageObj.limit,
      total: issue.count
    })
  } catch (error) {
    logger.error(error)
    res.status(500).json({ msg: '获取题目列表失败', code: 400 })
  }
}
/**
 * 新增
 * rmk:不用校验的请求参数
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
// 新增
async function issueAdd (req, res) {
  const FROM_ENUM = [1, 2, 3, 7, 8, 9, 10]
  for (const attr in req.body) {
    if (req.body[attr] === '' && (attr !== 'rmk' && attr !== 'question_address')) {
      return res.status(200).json({ msg: `${ Issue.tableAttributes[attr].comment }(${ attr })不能为空`, code: 40015 })
    }
    if (attr === 'question_from') {
      if (req.body[attr].length === 0) {
        return res.status(200).json({ msg: `${ Issue.tableAttributes[attr].comment }(${ attr })不能为空`, code: 40015 })
      } else {
        // 判断选定的值是否合理
        const str = req.body[attr].filter(item => !FROM_ENUM.includes(item))
        if (str.length > 0) {
          return res.status(200).json({ msg: `${ attr }未知的问题来源:${ str.join(',') }`, code: 40015 })
        }
      }
    }
  }
  const { question_name, question_cid, question_from, question_address, author, answer, stats, del, rmk } = req.body
  try {
    const count = await Issue.count()
    let id
    if (count === 0) {
      // 如果是首次创建 则使用随机生成的 ID
      const randomNum = Math.floor(Math.random() * 1000000).toString().padStart(5, '0')
      id = `102801${ randomNum }`
    } else {
      // 获取第一条数据的ID，并在此基础上递增生成后续数据的 ID
      const maxIdIssue = await Issue.findOne({ order: [['id', 'DESC']] })
      const maxId = parseInt(maxIdIssue.id) // 获取最大ID的数值部分
      id = maxId + 1
    }
    await Issue.create({ id, question_name, question_cid, question_from, question_address, author, answer, stats, del, rmk })
    res.status(200).json({ msg: 'OK', code: 0 })
  } catch (error) {
    logger.error(error)
    res.status(200).json({ msg: '新增题目失败', code: 500 })
  }
}

// 更新
async function issueUpd (req, res) {
  const FROM_ENUM = [1, 2, 3, 7, 8, 9, 10]
  for (const attr in req.body) {
    if (req.body[attr] === '' && (attr !== 'rmk' && attr !== 'question_address')) {
      return res.status(200).json({ msg: `${ Issue.tableAttributes[attr].comment }(${ attr })不能为空`, code: 40015 })
    }
    if (attr === 'question_from') {
      if (req.body[attr].length === 0) {
        return res.status(200).json({ msg: `${ Issue.tableAttributes[attr].comment }(${ attr })不能为空`, code: 40015 })
      } else {
        // 判断选定的值是否合理
        const str = req.body[attr].filter(item => !FROM_ENUM.includes(item))
        if (str.length > 0) {
          return res.status(200).json({ msg: `${ attr }未知的问题来源:${ str.join(',') }`, code: 40015 })
        }
      }
    }
  }
  const { id, question_name, question_cid, question_from, question_address, author, answer, stats, del, rmk } = req.body
  try {
    const course = await Issue.findOne({ where: { id } })
    if (course === null) {
      res.status(200).json({ msg: '查询用户失败', code: 0 })
    } else {
      await Issue.update({ question_name, question_cid, question_from, question_address, author, answer, stats, del, rmk }, {
        where: {
          id,
        }
      })
      res.status(200).json({ msg: 'OK', code: 0 })
    }
  } catch (error) {
    logger.error(error)
    res.status(200).json({ msg: error, code: 500 })
  }
}
// 获取详情
async function issueDetail (req, res) {
  const { id } = req.query
  try {
    const issue = await Issue.findOne({ where: { id } })
    if (issue === null) {
      res.status(200).json({ msg: '查询题目失败', code: 0 })
    } else {
      res.status(200).json({ msg: 'OK', code: 0, data: { data: issue } })
    }
  } catch (error) {
    logger.error(error)
    res.status(200).json({ msg: error, code: 500 })
  }
}
// 删除
async function issueDele (req, res) {

}
module.exports = { issueList, issueAdd, issueUpd, issueDetail, issueDele }
